/**
 * 个人中心JS
 */
var url = self.location.href.split("#");
if (url.length > 1) {
	self.location.href = url[0];
}
var v_agent_list = new Vue({
	el: '#agentListPage',
	data: {
		title: '我的下级代理',
		needBack: true,
		needRefresh: false,
		show: false,
		layer: 0,
		agents: [],
		parent: {
			id: '',
			name: ''
		}
	},
	methods: {
		init: function() {
			this.layer = 0;
			this.searchSubAgent();
		},
		goback: function() {
			if (this.layer > 0) {
				axios.post('/agent/get/' + this.parent.id)
				.then(function(resp) {
					if (resp.data.success) {
						var agent = resp.data.message;
						v_agent_list.title = (v_agent_list.layer == 0 ? '我的' : agent.parentName) + '下级代理'
						v_agent_list.searchSubAgent(1, {id: agent.parentId, name: agent.parentName});
					}
				})
				.catch(function (error) {
					console.log(error);
				});
			}
			this.layer--;
		},
		searchSubAgent: function(page, parentAgent) {
			var param = {
				page_pageNo: page || 1,
				page_pageSize: 5,
				page_sort: 'award.totalAmount_desc'
			};
			if (parentAgent) {
				param['filter_EQ_parent.id'] = parentAgent.id;
			}
			axios.post('/agent/sub/list', param)
			.then(function(resp) {
				if (resp.data.success) {
					v_agent_list.agents = resp.data.rows;
					if (parentAgent) {
						v_agent_list.parent.id = parentAgent.id;
						v_agent_list.parent.name = parentAgent.name;
					}
				}
			})
			.catch(function (error) {
			    console.log(error);
			});
		},
		gotoSubAgent: function(parentAgent) {
			this.layer++;
			this.title = parentAgent.name + '下级代理';
			$.router.load('#agentListPage');
			this.searchSubAgent(1, parentAgent);
		}
	}
});

var v_my_order_detail = new Vue({
	el: '#myOrderDetailPage',
	data: {
		title: '订单详情',
		needBack: true,
		needRefresh: false,
		show: false,
		order: {},
		orderTitles: [{
			orderNo: '订单号'
		},{
			orderTime_fmt: '下单时间'
		},{
			payChannel_fmt: '支付渠道'
		},{
			agentName: '购买代理商'
		},{
			receiver: '收货人 '
		},{
			phone: '收货人 电话'
		},{
			receiverAddress: '收货地址'
		},{
			express: '发货物流公司'
		},{
			waybillNo: '运单号'
		},{
			deliverTime: '发货时间'
		},{
			receiveTime: '收货时间'
		}]
	},
	methods: {
		goback: function() {
			
		}
	}
});

var v_my_order = new Vue({
	el: '#myOrderPage',
	data: {
		title: '我的订单',
		needBack: true,
		needRefresh: false,
		show: false,
		searchMobileNo: '',
		orders: [],
		unpaidOrders: [],
		deliveringOrders: [],
		shippedOrders: [],
		orders: [],
		orderNum:{}
	},
	methods: {
		init: function() {
			this.loadOrders(1, '', function(rows) {
				v_my_order.orders = rows
			});
			this.loadOrderNum();
		},
		showUnpaidOrders: function() {
			if (this.unpaidOrders.length == 0) {
				this.loadOrders(1, 'UNPAID', function(rows) {
					v_my_order.unpaidOrders = rows
				});
			}
		},
		showDeliveringOrders: function() {
			if (this.deliveringOrders.length == 0) {
				this.loadOrders(1, 'DELIVERING', function(rows) {
					v_my_order.deliveringOrders = rows
				});
			}
		},
		showShippedOrders: function() {
			if (this.shippedOrders.length == 0) {
				this.loadOrders(1, 'SHIPPED', function(rows) {
					v_my_order.shippedOrders = rows
				});
			}
		},
		goback: function() {
			// 返回
		},
		gotoPay: function(order) {
			$.alert('暂时不支持在线支付，请线下通过微信、支付、银行转账的方式付款给张果。');
		},
		gotoDetail: function(order) {
			v_my_order_detail.show = true;
			v_my_order_detail.order = order;
			v_my_order_detail.$nextTick(function() {
				$.router.load("#myOrderDetailPage");
			});
		},
		cancelOrder: function(order) {
			$.confirm('您确定要取消订单吗?', function () {
				axios.post('/order/my/cancel/' + order.id)
				.then(function(resp) {
					if (resp.data.success) {
						$.toast('订单已取消');
						v_my_order.init();
					} else {
						$.toast(resp.data.message);
					}
				})
				.catch(function (error) {
				    console.log(error);
				});
			});
		},
		searchOrders: function() {
			if (this.searchMobileNo) {
				$('div.buttons-tab').find('a.active').removeClass('active');
				$('div.buttons-tab').find('a[href="#orders_tab"]').addClass('active');
				$('div.tabs').find('div.tab.active').removeClass('active');
				$('#orders_tab').addClass('active');
				this.loadOrders(1, '', function(rows) {
					v_my_order.orders = rows
				});
			} else {
				$.toast('请输入手机号码');
			}
		},
		loadOrders: function(pageNo, status, callback) {
			// 初始化推荐人
			var param = {
				page_pageNo: pageNo,
				page_pageSize: 10,
				page_sort: 'orderTime_desc',
				filter_EQ_status: status,
			};
			if (!status) {
				param['filter_EQ_receiver.phone'] = this.searchMobileNo;
			}
			axios.post('/order/my/list', param)
			.then(function(resp) {
				if (resp.data.success) {
					$.each(resp.data.rows, function(i, row) {
						row.receiverAddress = row.province + row.city + row.region + row.address;
						if (row.status == 'UNPAID') {
							row.orderHeaderClass = 'alert-danger';
							row.canCancel = true;
						} else if (row.status == 'DELIVERING') {
							row.orderHeaderClass = 'alert-warning';
							row.canCancel = true;
						} else if (row.status == 'SUCCEED') {
							row.orderHeaderClass = 'alert-success';
							row.canCancel = false;
						} else if (row.status == 'CANCELLED' || row.status == 'CLOSE') {
							row.orderHeaderClass = 'alert-secondary';
							row.canCancel = false;
						} else {
							row.orderHeaderClass = 'alert-info';
							row.canCancel = false;
						}
					});
					callback && callback(resp.data.rows);
				}
			})
			.catch(function (error) {
			    console.log(error);
			});
		},
		loadOrderNum: function() {
			axios.post('/order/my/count')
			.then(function(resp) {
				if (resp.data.success) {
					v_my_order.orderNum = resp.data.message;
				}
			})
			.catch(function (error) {
			    console.log(error);
			});
		}
	}
});

var v_history_award = new Vue({
	el: '#historyAwardPage',
	data: {
		title: '历史奖金',
		needBack: true,
		needRefresh: false,
		show: false,
		awards: []
	},
	methods: {
		init: function() {
			// 初始化推荐人
			this.loadAward()
			
		},
		goback: function() {
			// 返回
		},
		gotoDetail: function(award){
			$.toast('跳转详情后续将会实现');
		},
		loadAward: function() {
			axios.post('/agent/award/log/my/list', {page_sort: 'awardTime_desc'})
			.then(function(resp) {
				if (resp.data.success) {
					v_history_award.awards = resp.data.rows;
				}
			})
			.catch(function (error) {
			    console.log(error);
			});
		}
	}
});

var v_modify_info = new Vue({
	el: '#modifyInfoPage',
	data: {
		title: '修改个人信息',
		needBack: true,
		needRefresh: false,
		show: false,
		form: {
			name: '',
			sex: true,
			mobileNo: '',
			qq:'',
			email: '',
			signature: '',
			bank: '',
			bankCard: '',
			zhifubao: '',
			wxPay: ''
		}
	},
	methods: {
		init: function() {
			axios.all([axios.post('/agent/current'), axios.post('/agent/account/current')])
			.then(axios.spread(function (agentResp, accountResp) {
				$.each(v_modify_info.form, function(key, value) {
					v_modify_info.form[key] = agentResp.data.message[key];
				});
//				v_modify_info.form = $.extend(v_modify_info.form, agentResp.data.message);
				$.each(accountResp.data.message, function(type, account) {
					if (type == 'BANK') {
						v_modify_info.form.bank = account.bank;
						v_modify_info.form.bankCard = account.accountNo;
					} else if (type == 'ZHIFUBAO') {
						v_modify_info.form.zhifubao = account.accountNo;
					} else if (type == 'WEIXIN') {
						v_modify_info.form.wxPay = account.accountNo;
					}
				});
			}))
			.catch(function (error) {
			    console.log(error);
			});
		},
		goback: function() {
			// 返回
		},
		postInfo: function() {
			axios.post('/agent/update/current/info', this.form)
			.then(function(resp) {
				if (resp.data.success) {
					$.router.load('#centerPage');
				} else {
					if ($.isArray(resp.data.message) && resp.data.message.length > 1) {
						$.alert(resp.data.message.join('<br>'));
					} else {
						$.toast(resp.data.message);
					}
				}
			})
			.catch(function (error) {
			    console.log(error);
			});
		}
	},
	updated: function() {// 不放在这里就比较坑爹
		$("#bankPicker").picker({
			toolbarTemplate: $('#bankPickerDiv').html(),
			cols: [{
				textAlign: 'center',
				values: banks
			    }],
			value: [v_modify_info.form.bank],
			onClose: function() {
				v_modify_info.form.bank = $("#bankPicker").val();
			}
		});
	}
});

var v_change_password = new Vue({
	el: '#changePasswordPage',
	data: {
		title: '修改密码',
		needBack: true,
		needRefresh: false,
		show: false,
		form: {
			oldPwd: '',
			newPwd: '',
			newPwd2: ''
		}
	},
	methods: {
		goback: function() {
			// 返回
		},
		postChange: function() {
			axios.post('/agent/change/password', this.form)
			.then(function(resp) {
				if (resp.data.success) {// 后台已经登出，这边随便刷个页面就会跳入到登录页面了
					$.toast('密码已更新，请重新登录');
					setTimeout(function(){
						self.location.href = '/center';
					}, 1000);
				}
			})
			.catch(function (error) {
			    console.log(error);
			});
		}
	}
});

v_head_popup = new Vue({
	el: 'div.popup-header',
	data: {
		headUrl: '',
		headImgUrl: ''
	},
	methods: {
		postHeader: function() {
			axios.post('/agent/change/head', {headUrl: this.headImgUrl})
			.then(function(resp) {
				if (!resp.data.success) {
					$.toast(resp.data.message);
				}
				v_center.agent.headUrl = v_head_popup.headImgUrl;
			})
			.catch(function (error) {
			    console.log(error);
			});
		},
		loadImage: function() {
			this.headImgUrl = this.headUrl;
			v_head_popup.$foreUpdate();
		},
		closePopup: function() {
			
		}
	}
});

v_center = new Vue({
	el: '#centerPage',
	data: {
		title: '个人中心',
		needBack: false,
		needRefresh: false,
		navs: $.extend(true, [], navs, [{}, {}, {active: 'active'}]),
		agent: {},
		functions: [{
			name: '代理管理',
			menus: [{
				name: '下级代理',
				vm: v_agent_list
			}, {
				name: '添加代理',
				vm: v_agent_add
			}]
		}, {
			name: '订单奖金',
			menus: [{
				name: '我的订单',
				vm: v_my_order
			}, {
				name: '收货地址管理',
				vm: v_receiver
			}, {
				name: '历史奖金',
				vm: v_history_award
			}]
		}, {
			name: '个人资料',
			menus: [{
				name: '修改个人信息',
				vm: v_modify_info
			}, {
				name: '修改密码',
				vm: v_change_password,
			}]
		}]
	},
	created: function() {
		axios.post('/agent/current')
		.then(function(resp) {
			if (resp.data.success) {
				v_center.agent = resp.data.message;
				if (!v_center.agent.headUrl) {
					v_center.agent.headUrl = v_center.agent.sex ? '/images/header_male.png' : '/images/header_female.png';
				}
			}
		})
		.catch(function (error) {
		    console.log(error);
		});
	},
	methods: {
		gotopage: function(menu) {
			menu.vm.show = true;
			menu.vm.init && menu.vm.init();
			menu.vm.$nextTick(function() {
				$.router.load('#' + $(menu.vm.$el).attr('id'));  //加载内联页面
			});
		},
		changeHeader: function() {
			v_head_popup.headImgUrl = this.agent.headUrl;
			v_head_popup.headUrl = '';
			$.popup($(v_head_popup.$el));
		},
		logout: function() {
			self.location.href = '/logout';
		},
		showQrCode: function() {
			var url = self.location.href.replace(self.location.pathname, '');
			var $modal = $.modal({
				title:  '邀请二维码',
				text:$('#qrCodeDiv').html(),
				buttons: [{
			          text: '下　载',
			          close: false,
			          onClick: function() {
			        	  $.toast('按住图片3秒，根据菜单选择保存图片到本地');
			          }
			        }, {
			          text: '确　定',
			          close: true
			        }]
			});
			$('div.modal.modal-in').find('img').attr('src', '/agent/current/qrcode?serverUrl=' + encodeURIComponent(url));
		}
	}
});

var banks = [
	'工商银行',
	'建设银行',
	'中国银行',
	'农业银行',
	'交通银行',
	'邮政银行',
	'招商银行',
	'兴业银行',
	'中信银行',
	'光大银行',
	'民生银行',
	'广发银行',
	'华夏银行',
	'浦发银行',
	'平安银行'
	];

// 能自动跳转到想要的页面
var url = self.location.href.split("#");
if (url.length > 1 && url[1] == 'myOrderPage') {
	v_my_order.show = true;
	// 跳转有点麻烦，首先要vue完成
//	v_my_order.$nextTick(function() {
//		//其次是msui完成
//		$.router.load('#myOrderPage');
//	})
}